package com.hmkj.core.api.zhutong.util;

import com.hmkj.core.exception.BussinessException;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.Setter;

import java.net.URLEncoder;
import java.util.function.Consumer;

/**
 * 助通短信工具类
 *
 * @author eproo
 * @create 2017-09-21 18:48
 */
public class ZhuTongSmsUtil {
    @Setter
    private String signature;   /*平台短信签名*/
    @Setter
    private String username;    /*助通短信接口用户名*/
    @Setter
    private String password;    /*助通短信接口密码*/
    @Setter
    private String smsUrl;      /*助通短信接口地址*/
    @Setter
    private boolean enable;     /*短信接口是否启用*/

    private static ZhuTongSmsUtil instance;

    public ZhuTongSmsUtil(String signature,String username, String password, String smsUrl, boolean enable) {
        this.signature = signature;
        this.username = username;
        this.password = password;
        this.smsUrl = smsUrl;
        this.enable = enable;
    }

    public ZhuTongSmsUtil(Consumer<ZhuTongSmsUtil> consumer) {
        consumer.accept(this);
    }

    /**
     * @param phone
     * @param msg
     * @return String
     * @throws
     * @author tianyh
     * @Description
     */
    public String sendSmsByPost(String phone, String msg) {
        if (!enable) return null;
        if (StrUtil.isBlank(phone)) throw new BussinessException("手机号不能为空");
        if (StrUtil.isBlank(msg)) throw new BussinessException("短信内容不能为空");
        String tkey=TimeUtil.getNowTime("yyyyMMddHHmmss");
        String xh ="";
        try {
            msg= URLEncoder.encode(signature+msg,"utf-8");
            String param="url="+smsUrl+"&username="+username+"&password="+MD5Gen.getMD5(MD5Gen.getMD5(password)+tkey)+"&tkey="+tkey+"&mobile="+phone+"&content="+msg+"&xh="+xh;
            String ret=HttpRequest.sendPost(smsUrl, param);
            System.out.println("ret:"+ret);
            System.out.println(param);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
